<template>
  <view class="inventory-add-container">
    <view class="page-header">
      <text class="page-title">新增库存</text>
    </view>

    <view class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label required">物品编码</text>
          <input v-model="formData.item_code" class="form-input" placeholder="请输入物品编码（唯一标识）" />
          <text v-if="errors.item_code" class="error-text">{{ errors.item_code }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">物品名称</text>
          <input v-model="formData.item_name" class="form-input" placeholder="请输入物品名称" />
          <text v-if="errors.item_name" class="error-text">{{ errors.item_name }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">物品类型</text>
          <radio-group @change="onItemTypeChange" class="radio-group">
            <label class="radio-label">
              <radio value="1" :checked="formData.item_type === 1" />
              <text>药品</text>
            </label>
            <label class="radio-label">
              <radio value="2" :checked="formData.item_type === 2" />
              <text>医疗器械</text>
            </label>
            <label class="radio-label">
              <radio value="3" :checked="formData.item_type === 3" />
              <text>耗材</text>
            </label>
            <label class="radio-label">
              <radio value="4" :checked="formData.item_type === 4" />
              <text>其他</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label">分类</text>
          <input v-model="formData.category" class="form-input" placeholder="如：麻醉药品、检查器材等" />
        </view>

        <view class="form-item">
          <text class="form-label">规格型号</text>
          <input v-model="formData.specification" class="form-input" placeholder="请输入规格型号" />
        </view>

        <view class="form-item">
          <text class="form-label">单位</text>
          <input v-model="formData.unit" class="form-input" placeholder="如：盒、瓶、支、个" />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">库存信息</text>
        
        <view class="form-item">
          <text class="form-label">当前库存</text>
          <input v-model="formData.current_quantity" type="number" class="form-input" placeholder="请输入当前库存数量" />
        </view>

        <view class="form-item">
          <text class="form-label">最低库存</text>
          <input v-model="formData.min_quantity" type="number" class="form-input" placeholder="库存预警阈值" />
        </view>

        <view class="form-item">
          <text class="form-label">最大库存</text>
          <input v-model="formData.max_quantity" type="number" class="form-input" placeholder="最大库存容量" />
        </view>

        <view class="form-item">
          <text class="form-label">单价（元）</text>
          <input v-model="formData.unit_price" type="digit" class="form-input" placeholder="采购单价" />
        </view>

        <view class="form-item">
          <text class="form-label">存放位置</text>
          <input v-model="formData.storage_location" class="form-input" placeholder="如：药房A区、器械室3号柜" />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">供应商信息</text>
        
        <view class="form-item">
          <text class="form-label">供应商</text>
          <input v-model="formData.supplier" class="form-input" placeholder="请输入供应商名称" />
        </view>

        <view class="form-item">
          <text class="form-label">生产厂家</text>
          <input v-model="formData.manufacturer" class="form-input" placeholder="请输入生产厂家" />
        </view>

        <view class="form-item">
          <text class="form-label">批次号</text>
          <input v-model="formData.batch_no" class="form-input" placeholder="请输入批次号" />
        </view>

        <view class="form-item">
          <text class="form-label">过期日期</text>
          <picker mode="date" :value="expiryDateValue" @change="onExpiryDateChange" class="date-picker">
            <view class="picker-input">
              {{ expiryDateValue || '请选择过期日期' }}
            </view>
          </picker>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">其他信息</text>
        
        <view class="form-item">
          <text class="form-label">条形码</text>
          <input v-model="formData.barcode" class="form-input" placeholder="请输入条形码" />
        </view>

        <view class="form-item">
          <text class="form-label">二维码内容</text>
          <input v-model="formData.qrcode" class="form-input" placeholder="JSON格式或文本内容" />
        </view>

        <view class="form-item">
          <text class="form-label">描述</text>
          <textarea v-model="formData.description" class="form-textarea" placeholder="请输入物品描述" />
        </view>

        <view class="form-item">
          <text class="form-label">使用说明</text>
          <textarea v-model="formData.usage_note" class="form-textarea" placeholder="请输入使用说明" />
        </view>

        <view class="form-item">
          <text class="form-label">管控物品</text>
          <switch :checked="formData.is_controlled" @change="onControlledChange" color="#3b82f6" />
          <text class="form-hint">如麻醉药品、精神类药品</text>
        </view>

        <view class="form-item">
          <text class="form-label">状态</text>
          <radio-group @change="onStatusChange" class="radio-group">
            <label class="radio-label">
              <radio value="1" :checked="formData.status === 1" />
              <text>正常</text>
            </label>
            <label class="radio-label">
              <radio value="4" :checked="formData.status === 4" />
              <text>停用</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn-submit" @click="handleSubmit">提交</button>
        <button class="btn-cancel" @click="handleCancel">取消</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'

const inventoryObj = uniCloud.importObject('dh-inventory')

const formData = reactive({
  item_code: '',
  item_name: '',
  item_type: 4,
  category: '',
  specification: '',
  unit: '',
  current_quantity: 0,
  min_quantity: 0,
  max_quantity: 0,
  unit_price: 0,
  supplier: '',
  manufacturer: '',
  storage_location: '',
  batch_no: '',
  expiry_date: null,
  barcode: '',
  qrcode: '',
  description: '',
  usage_note: '',
  is_controlled: false,
  status: 1
})

const errors = reactive({
  item_code: '',
  item_name: ''
})

const expiryDateValue = computed(() => {
  if (!formData.expiry_date) return ''
  const date = new Date(formData.expiry_date)
  return date.toISOString().split('T')[0]
})

function onItemTypeChange(e) {
  formData.item_type = parseInt(e.detail.value)
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

function onControlledChange(e) {
  formData.is_controlled = e.detail.value
}

function onExpiryDateChange(e) {
  const dateStr = e.detail.value
  if (dateStr) {
    formData.expiry_date = new Date(dateStr).getTime()
  } else {
    formData.expiry_date = null
  }
}

function validateForm() {
  let isValid = true
  
  if (!formData.item_code || formData.item_code.trim().length === 0) {
    errors.item_code = '请输入物品编码'
    isValid = false
  } else {
    errors.item_code = ''
  }
  
  if (!formData.item_name || formData.item_name.trim().length === 0) {
    errors.item_name = '请输入物品名称'
    isValid = false
  } else {
    errors.item_name = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    const submitData = {
      ...formData,
      current_quantity: parseInt(formData.current_quantity) || 0,
      min_quantity: parseInt(formData.min_quantity) || 0,
      max_quantity: parseInt(formData.max_quantity) || 0,
      unit_price: parseFloat(formData.unit_price) || 0
    }
    
    const result = await inventoryObj.createInventory(submitData)
    if (result.code === 201 || result.code === 200) {
      uni.showToast({ title: '创建成功', icon: 'success' })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '创建失败', icon: 'none' })
    }
  } catch (err) {
    console.error('创建失败:', err)
    uni.showToast({ title: err.message || '创建失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.inventory-add-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-container {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
}

.form-section {
  margin-bottom: 40rpx;
  padding-bottom: 30rpx;
  border-bottom: 1px solid #e5e7eb;
  
  &:last-of-type {
    border-bottom: none;
  }
}

.section-title {
  display: block;
  font-size: 30rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
  border-left: 4px solid #3b82f6;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: 500;
}

.form-label.required::before {
  content: '* ';
  color: #dc3545;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #fff;
}

.form-textarea {
  min-height: 150rpx;
}

.date-picker {
  width: 100%;
}

.picker-input {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #fff;
  color: #333;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 40rpx;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.form-hint {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #6b7280;
}

.error-text {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #dc3545;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 50rpx;
}

.btn-submit, .btn-cancel {
  flex: 1;
  padding: 25rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  border: none;
  cursor: pointer;
}

.btn-submit {
  background-color: #007bff;
  color: #fff;
}

.btn-cancel {
  background-color: #6c757d;
  color: #fff;
}
</style>

